/**
 * 
 */
(function($){
	
	var map = null;
	var infoWindow = null;
	var myPosition = null;
	var siteData = new Array();
	var siteNormal = new Array();
	var siteAbnormal = new Array();
	var customizeTimer = null;
	var isFirst = 1;// 默认第一次
	
	/**
	 * 初始化地图
	 */
	var initMap = function(){
		// 初始化地图
		map = new AMap.Map('myMap', {
	        resizeEnable: true,
	        zoom:11,
	        center: [108.942531,34.270538],
	        scrollWheel:true,
	    });
		// 地图监听事件：当地图加载完成后执行
		map.on('complete', function() {
	        //设置城市
	        map.setCity('西安市');
	        getCurrentLocation();// 获取用户当前GPS位置
	    });
	};
	
	/**
	 * 定义地图气泡对象
	 */
	var initWindowsInfo = function(){
		infoWindow = new AMap.InfoWindow({
			offset: new AMap.Pixel(0, -30),
			closeWhenClickMap:true,
		})
	}
	
	/**
	 * 获取用户当前位置
	 */
	var getCurrentLocation = function(){
		map.plugin('AMap.Geolocation', function () {
		    geolocation = new AMap.Geolocation({
		        enableHighAccuracy: true,//是否使用高精度定位，默认:true
		        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
		        maximumAge: 0,           //定位结果缓存0毫秒，默认：0
		        convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
		        showButton: true,        //显示定位按钮，默认：true
		        buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
		        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)	
		        showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
		        showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
		        panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
		        zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
		    });
		    // 开始定位
		    geolocation.getCurrentPosition();
		    AMap.event.addListener(geolocation, 'complete', getCurrentLocationOnComplate);//返回定位信息
		    AMap.event.addListener(geolocation, 'error', getCurrentLocationOnError);      //返回定位出错信息
		});
	};
	
	// 定位成功
	var getCurrentLocationOnComplate = function(data){
		var currentLocaltion = data.position;
		
		map.setCenter([currentLocaltion.getLng(), currentLocaltion.getLat()]);
	    if(null == myPosition){
	    	myPosition = new AMap.Marker({
	            position: [data.position.getLng(), data.position.getLat()],
	            draggable: false,
	            cursor: 'move',
	            icon: './resources/images/loc_ok.png'
	        });
	    	// 设置鼠标划过点标记显示的文字提示
	    	myPosition.setTitle('我的位置');
	    	myPosition.setMap(map);
	        map.setZoom(16);
	    } else {
	    	myPosition.setPosition([data.position.getLng(), data.position.getLat()]);
	    }
	    // 初始化点
	    map.setFitView();
	    searchBike(currentLocaltion.getLng(), currentLocaltion.getLat());
	};
	
	// 定位失败
	var getCurrentLocationOnError = function(data){
		$.alert('定位失败，请重新定位并尝试。');
//		searchBike(108.914304, 34.20685);//测试所用
	};
	
	/**
	 * 根据定位位置信息获取周围站点信息
	 * @param valLng
	 * @param valLat
	 * @returns
	 */
	function searchBike(valLng, valLat){
		$.ajax({
			 type:'post',
			 url:'getSearch',
			 data:{
				 lng: valLng,
				 lat: valLat,
				 radius: "1500",
				 isFirst: isFirst,
				 
			 },
			 dataType:'json',
			 success:function(data){
				 isFirst = 0;
				 //siteData = data;
				 if(null != siteAbnormal && siteAbnormal.length > 0){
					 clearMap(siteNormal);
				 }
					if(null != siteAbnormal && siteAbnormal.length > 0){
					 clearMap(siteAbnormal);
				 }
				for(var i = 0; i < data.length; i++){
					 var siteInfo = data[i];
					 siteInfo.isNormal = 'exception';
					 if(siteInfo.siteState == 1){
						 siteInfo.isNormal = 'normal';
					 }
					 siteInfo.id = i;
					 addMarker(siteInfo);
				}
				map.setFitView();
			 }
		 });  
	}
	
	/**
	 * 添加标注点
	 */
	var addMarker = function(data){
		//	var siteInfo = siteData;
		var title = '' + data.sitename, content = [];
		var lnglat = new AMap.LngLat(data.longitude, data.latitude);
		var id = "marker_bike_" + data.id;
		var siteState = 1;
		var icon = './resources/images/zxc_g1.png';
		
		if ('normal' == data.isNormal) {
			id = "marker_bike_" + data.id;
		} else if ('exception' == data.isNormal) {
			id = "marker_exception_bike_" + data.id;
			icon = './resources/images/zxc_r1.png';
			siteState = 2;
		} else {
			id = "marker_all_bike_" + data.id;
			icon = './resources/images/zxc_r1.png';
			siteState = 2;
		}
	
		var marker = new AMap.Marker({
			id : id,
			siteState : siteState,
			icon : icon,
			position : lnglat,
			map : map
		});
		marker.siteId = data.siteid;
		closeInfoWindow();
		// 鼠标点击marker弹出自定义的信息窗体
		AMap.event.addListener(marker, 'click', function(e) {
			map.setCenter(e.target.getPosition());
			if(map.getZoom() < 17){
				map.setZoom(17);
			};
			map.setFitView(e.target.getPosition());
			var content = getWindowInfoContent(e.target.siteId);
			infoWindow.setContent(content);
			infoWindow.open(map, e.target.getPosition());
		});// 注册监听，当选中某条记录时会触发
	}
	
	var getWindowInfoContent = function(siteId){
		 var url = "get/site/"+siteId;
		 var result = $.ajax({
			 type:'post',
			 url:url,
			 data:{},
			 async:false,
			 dataType:'json'
		 });
		 var data = null;
		 if(result && result.responseText){
			 data = JSON.parse(result.responseText);
		 }
		 if(data){
			 var content = [];
			 content.push("<div style='font-size:10px;'>");
			 content.push("网点状态："+(data.siteState=='1'?'正常':'异常'));
			 content.push("网点编号："+siteId);
			 content.push("网点名称："+data.sitename);
			 content.push("网点地址："+data.location);
			 content.push("可租车辆数："+(data.locknum-data.emptynum));
			 content.push("可还空位数："+data.emptynum);
			 content.push("更新时间："+data.updateTime);
			 content.push("</div>");
		 }
		 var html = "";
		 html = content.join("<br/>");
		 return html;
	}
	
	var startTimers = function(){
		customizeTimer = setInterval(function(){
			//$.alert('数据已刷新');
			synchronizeData();
		}, 30000);
	}
	
	var synchronizeData = function(){
		var url = "synchronize?t="+new Date().getTime();
		 var result = $.ajax({
			 type:'post',
			 url:url,
			 data:{},
			 dataType:'json'
		 });
	}
	
	/**
	 * 删除地图上覆盖物
	 */
	var clearMap = function (overlayers) {
		map.remove(overlayers)
	}
	
	/**
	 * 删除地图上所有的覆盖物
	 * @returns
	 */
	var clearMapAll = function () {
		map.clearMap();
	}
	
	/**
	 * 关闭地图信息气泡窗体
	 * @returns
	 */
	function closeInfoWindow() {
		map.clearInfoWindow();
	}
	
	/**
	 * 启动重新定位功能
	 */
	var reloadLocation = function(){
		// 重新定位
		$('#reload-local').on('click',function (){
			map.setCenter(myPosition.getPosition());
			nowZoom = 17;
			map.setZoom(nowZoom);
		});
	}
	
	var init = function(){
		initMap();
		initWindowsInfo();
		synchronizeData();
		startTimers();// 启动定时器
		reloadLocation();
	}
	
	$(function(){
		
		init();
		
	});
})($);